var ChatDef = new Class({
	initialize: function(idchat){
		//Traer chat de la base de datos
		this.id = idchat;
		this.privates = {};
		this.nprivates = 1;
		this.clients = {};
		this.privateindexes = [];
	}
	
	//Load chat from DATABASE.
	,loadChat: function(){
		if(true) return true;
		else return false;
	}
	//Conecta un cliente al chat público
	,connectClient: function(client){
		this.clients[ client.id ] = {
			id: client.id
			,connectTime: new Date()
			,privates : []
		};
	}
	
	//byClient tries to open a private chat sesion with toClient
	,makePrivateWith: function(byClient, toClient){
		if(this.privateindexes.length){ // Si hay indexes por cubrir
			var index = this.privateindexes.pop();
		}else{
			var index = this.nprivates;
			this.nprivates++;
		}
		
		this.privates[index] = {};
		this.privates[index][byClient.id] = {id: client.id, openTime: new Date(), maker: true};
		this.privates[index][toClient.id] = {id: client.id, openTime: new Date(), maker: false};
		
		this.clients[byClient.id].privates.push(index);
		this.clients[toClient.id].privates.push(index);
		
		return index;
	}
	//Lib indica el privado que se acaba de liberar.
	,orderIndexPrivates: function(lib){
		if(p == this.privates-1){
			this.privates = p;
			while(this.privateindexes[ this.privateindexes.length ] == this.privates-1){
				this.nprivates = this.privateindexes.pop();
			}
		} else {
			this.privateindexes.push(p);
			this.privateindexes.sort();
		}
	}
	
	//Cuando el usuario se desconecta se ejecuta para cerrar los privados que tiene abiertos.
	,closePrivates: function(byClient){
		this.clients[byClient.id].privates.each(function(p){
			if( this.privates[p] && this.privates[p][byClient.id] ) {
				this.orderIndexPrivates(p);
				delete this.privates[p];
				return true;
			} else return false;
		}, this);
	}
	//Save to DB.
	//Returns lista de usuarios.
	,newMessage: function(client, msg, room){
		if( !this.clients[ client.id ] ) return {};
		if(room !== 0 && !(this.privates[room] && this.privates[room][client.id]) ) return {};
		
		if(typeof(msg) != "string") return {};
		//Save to DB.
		
		if(room === 0) return this.clients;
		else return this.privates[room];
	}
	,clientDisconnected: function(client){
		this.closePrivates(client);
		delete this.clients[client.id];
	}
});

//If idchat isn't a existent chat returns null.
exports.loadChat = function(idchat){
	var c = new ChatDef(idchat);
	if( c.loadChat() ) return c;
	else return null;
}
